// 全局请求封装
const base_url = 'https://jingqu.kuxia.top';

export default (params) => {
  let url = params.url;
  let method = params.method || "GET";
  let data = params.data || {};
  let header = {};

  if (method == "POST") {
    header = {
      'content-type': 'application/json'
    };
  }

  // 获取本地token
  const token = wx.getStorageSync("token");
  if (token) {
    header['Authorization'] = 'Bearer ' + token;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: base_url + url,
      method: method,
      header: header,
      data: data,
      success(response) {
        const res = response.data;
        if (res.statusCode == 200) {
          resolve(res);
        } else {
          wx.clearStorageSync();
          switch (res.statusCode) {
            case 401:
              wx.showModal({
                title: "提示",
                content: "请登录",
                showCancel: false,
                success(res) {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: "/pages/login/index",
                    });
                  }, 1000);
                },
              });
              break;
            case 404:
              wx.showToast({
                title: '请求地址不存在...',
                duration: 2000,
              });
              break;
            default:
              wx.showToast({
                title: '请重试...',
                duration: 2000,
              });
              break;
          }
        }
      },
      fail(err) {
        console.log(err);
        if (err.errMsg.indexOf('request:fail') !== -1) {
          wx.showToast({
            title: '网络异常',
            icon: "error",
            duration: 2000
          });
        } else {
          wx.showToast({
            title: '未知异常',
            duration: 2000
          });
        }
        reject(err);
      },
      complete() {
        wx.hideLoading();
        wx.hideToast();
      }
    });
  }).catch((e) => {});
};